/**
 * @file auditPurchasePop.js
 * @Date 2023-09-24, 周日, 16:44
 * @description 文件说明
 *审核管理产品审核更改订单信息js
 */
$(function () {
    /******************初始化部分******************/
    const form = layui.form
    // 获取URL中的查询参数部分
    const queryString = window.location.search;
    // 解析查询参数字符串，将其转换为对象
    const urlParams = new URLSearchParams(queryString);
    // 获取associateId参数的值 订单的id
    const associateId = Number(urlParams.get('associateId'));
    // 定制产品申请id
    const requestId=Number(urlParams.get('requestId'))
    const customProductId=Number(urlParams.get('id'))
    const productName=urlParams.get('productName')
    let dataEnsureRightType=0
    console.log('requestId', requestId)
    console.log('productName', productName)
    // 审核记录id
    const id =Number( urlParams.get('id'))
    if (associateId) {
        // 获取订单详情
        $.ajax({
            timeout:30000,
            url: window.Http + `/orderProduct/${associateId}`,
            type: 'GET',
            headers: {
                'Authorization': "Bearer " + sessionStorage.getItem('Token')
            },
            success: function (res) {
                if (res.code === 200) {
                    const auditFormData = res.data;
                    dataEnsureRightType=auditFormData.dataEnsureRightType
                    // 访问信息和使用信息处理
                    auditFormData.useType = auditFormData.customerBillingTypeLocal;
                    auditFormData.buyType = auditFormData.customerBillingType;
                    auditFormData.buyNum =
                        auditFormData.customerCanUseDay || auditFormData.customerCanUseNumber || auditFormData.customerCanUseRecords
                    auditFormData.useNum =
                        auditFormData.customerCanUseDayLocal || auditFormData.customerCanUseNumberLocal
                    // 表单赋值
                    form.val('auditForm', auditFormData);
                } else {
                    layer.msg(res.msg)
                }
            }
        })
    } else if(requestId&&productName){
        $.ajax({
            url: window.Http + `/CustomizeRequest/${requestId}`,
            type: 'GET',
            headers: {
                'Authorization': "Bearer " + sessionStorage.getItem('Token')
            },
            success: function (res) {
                if (res.code === 200) {
                    console.log('res',res )
                    $('#remark').text('备注')
                    $('#agreeBtn').text('确定')
                    $('#rejectBtn').text('取消')
                    form.val('auditForm',{
                        "productName":productName||"无",
                        "createBy":res.data.createBy,
                        "phone":res.data.phone,
                    })
                } else {
                    layer.msg(res.msg||'操作失败')
                }
            }
        })
    }
    else {
        layer.msg('信息错误')
    }
    /******************事件处理部分******************/
        // 通过按钮
    let index = parent.layer.getFrameIndex(window.name);
    $('#agreeBtn').on('click',function () {
        console.log(`index:${index}`)
        const buyDataProductForm=getFormData()
      if (requestId&&productName){
          $.ajax({
              url: window.Http + '/dataProduct/order',
              type: 'POST',
              headers: {
                  'Authorization': "Bearer " + sessionStorage.getItem('Token')
              },
              contentType: "application/json;charset=utf-8",
              data: JSON.stringify(buyDataProductForm),
              success: function (res) {
                  if (res.code === 200) {
                      layer.msg('订单自动生成成功')
                      parent.layer.close(index);
                      setTimeout(function (){
                      layer.closeAll(); //疯狂模式，关闭所有层
                      },1000)
                  } else {
                      layer.msg(res.msg)
                  }
              }
          })
      }else {
          auditResultReq(getAuditData(),2).then(res=>{
              // 关闭弹窗
              layer.msg('操作成功')
              parent.layer.close(index);
          })
      }
    })
    // 驳回按钮
    $('#rejectBtn').on('click',function () {
        auditResultReq(getAuditData(),3).then(res=>{
            // 关闭弹窗
            layer.msg('操作成功')
            parent.layer.close(index);
        })
    })
    /******************功能函数部分******************/
    /**
     * @Date：2023-09-24, 周日, 18:57
     * @description:函数描述 获取表单的数据转换为提交的格式 不包括status
     * @return Object 转换好对象
     */
    function getFormData() {
        const formData = form.val('auditForm')
        // 最后提交的数据
        const submitData = {
            auditResult: formData.auditResult,
            customerBillingType: Number(formData.buyType),//购买计费类别
            customerBillingTypeLocal: Number(formData.useType),//使用计费类别
            customerCanUseDay: 0,
            customerCanUseDayLocal: 0,
            customerCanUseNumber: 0,
            customerCanUseNumberLocal: 0,
            customerCanUseRecords: 0,
            dataEnsureRightType: Number(formData.dataEnsureRightType),
            dataFreedomType: Number(formData.dataFreedomType),
            customerProductPrice:Number(formData.customerProductPrice),
            productId:customProductId
        }
        switch (submitData.customerBillingType) {
            case 0:
                submitData.customerCanUseNumber =Number(formData.buyNum);
                break;
            case 2:
                submitData.customerCanUseRecords = Number(formData.buyNum);
                break;
            case 4:
                submitData.customerCanUseDay = Number(formData.buyNum);
                break;
            default:
                layer.msg('访问方式错误');
                break;
        }
        switch (submitData.customerBillingTypeLocal) {
            case 0:
                submitData.customerCanUseNumberLocal =Number(formData.useNum);
                break;
            case 4:
                submitData.customerCanUseDayLocal = Number(formData.useNum);
                break;
            default:
                layer.msg('使用方式错误');
                break;
        }
        return submitData;
    }

    function getAuditData() {
        const formData = form.val('auditForm')
        // 最后提交的数据
        const submitData = {
            auditResult: formData.auditResult,
            billingType: Number(formData.buyType),//购买计费类别
            billingTypeLocal: Number(formData.useType),//使用计费类别
            canUseDay: 0,
            canUseDayLocal: 0,
            canUseNumber: 0,
            canUseNumberLocal: 0,
            canUseRecords: 0,
            dataEnsureRightType:dataEnsureRightType,
            dataFreedomType: Number(formData.dataFreedomType),
            productPrice:Number(formData.customerProductPrice),
            id:customProductId,
            sharedType:Number(formData.sharedType)
        }
        switch (submitData.billingType) {
            case 0:
                submitData.canUseNumber =Number(formData.buyNum);
                break;
            case 2:
                submitData.canUseRecords = Number(formData.buyNum);
                break;
            case 4:
                submitData.canUseDay = Number(formData.buyNum);
                break;
            default:
                layer.msg('访问方式错误');
                break;
        }
        switch (submitData.billingTypeLocal) {
            case 0:
                submitData.canUseNumberLocal =Number(formData.useNum);
                break;
            case 4:
                submitData.canUseDayLocal = Number(formData.useNum);
                break;
            default:
                layer.msg('使用方式错误');
                break;
        }
        return submitData;
    }
    /**
     * @Date：2023-09-24, 周日, 19:13
     * @description:函数描述 审核结果提交请求
     * @return Promise
     * @param data {Object} 表单的其他数据
     * @param status {number} 2表示通过 3表示驳回
     */
    function auditResultReq(data, status) {
        return new Promise(function (resolve, reject) {
            $.ajax({
       timeout:30000,
                    url: window.Http + '/audit/log/operate',
                    type: "POST",
                    headers: {
                        'Authorization': "Bearer " + sessionStorage.getItem('Token')
                    },
                    data: JSON.stringify({
                        ...data,
                        status
                    }),
                    contentType: 'application/json;charset=utf-8',
                    success: function (res) {
                        if (res.code === 200) {
                            resolve(res)
                        } else {
                            reject(new Error(res.msg))
                        }
                    }
                }
            )
        })
    }
})